#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author : bird.zhang@ximalaya.com


import sys
import random

from . import argparser
from .util import random_util


def gen_passwd(args):
    length = args.length
    digit_cnt = args.digit_cnt
    lower_char_cnt = args.lower_char_cnt
    upper_char_cnt = args.upper_char_cnt
    special_char_cnt = args.special_char_cnt

    # for debug
    if args.debug:
        print('before refactor:')
        print('length = %d' % length)
        print('digit_cnt = %d' % digit_cnt)
        print('lower_char_cnt = %d' % lower_char_cnt)
        print('upper_char_cnt = %d' % upper_char_cnt)
        print('special_char_cnt = %d' % special_char_cnt)

    if digit_cnt < 0:
        digit_cnt = 0
    if lower_char_cnt < 0:
        lower_char_cnt = 0
    if upper_char_cnt < 0:
        upper_char_cnt = 0
    if special_char_cnt < 0:
        special_char_cnt = 0
    if length < (digit_cnt + lower_char_cnt + upper_char_cnt + special_char_cnt):
        length = digit_cnt + lower_char_cnt + upper_char_cnt + special_char_cnt

    # for debug
    if args.debug:
        print('after refactor:')
        print('length = %d' % length)
        print('digit_cnt = %d' % digit_cnt)
        print('lower_char_cnt = %d' % lower_char_cnt)
        print('upper_char_cnt = %d' % upper_char_cnt)
        print('special_char_cnt = %d' % special_char_cnt)

    passwd = []
    for i in range(digit_cnt):
        passwd += random_util.random_digit()
    for i in range(lower_char_cnt):
        passwd += random_util.random_lower_char()
    for i in range(upper_char_cnt):
        passwd += random_util.random_upper_char()
    for i in range(special_char_cnt):
        passwd += random_util.random_special_char()
    for i in range(length - digit_cnt - lower_char_cnt - upper_char_cnt - special_char_cnt):
        passwd += random_util.random_char()

    random.shuffle(passwd)

    return passwd


def run():
    # if len(sys.argv) == 1:
    #     sys.argv.append('--help')

    parser = argparser.gen_pymkpasswd_parse()
    args = parser.parse_args()

    print(''.join(gen_passwd(args)))
